package com.exer;

import java.util.Arrays;

/**
 * 比较两个字符串中最大相同子串
 str1 = "abcwerthelloyuiodefabcdef";str2 = "cvhellobnm"
 提示：将短的那个串进行长度依次递减的子串与较长的串比较。
 */
public class StringDemo3 {

    public static void main(String[] args) {
        String str1= "abcwerthelloyuiodefabcdef",str2 = "cvhellobnm";
        str1 = "abcwerthello1yuiodefabcdef";
        str2 = "cvhello1bnmabcdef";
//        System.out.println(compareString(str1,str2));
        String[] strings = compareString2(str1, str2);
        System.out.println(Arrays.toString(strings));
    }
    //假设最大子串只有一个
    public static String compareString(String str1 ,String str2){
        String longStr = str1.length() >= str2.length() ? str1 : str2;
        String shortStr = str1.length() > str2.length() ? str2 : str1;
        int length = shortStr.length();
        for (int i = 0; i < length; i++) {
            for (int x = 0,y=length-i; y <=length ; x++,y++) {
                String str = shortStr.substring(x, y);
                if(longStr.contains(str)){
                    return str;
                }
            }
        }
        return null;
    }
    // 如果存在多个长度相同的最大相同子串
    // 此时先返回String[]，后面可以用集合中的ArrayList替换，较方便
    public static String[] compareString2(String str1 ,String str2){
        if(str1 != null && str2 !=null) {
            String longStr = str1.length() >= str2.length() ? str1 : str2;
            String shortStr = str1.length() > str2.length() ? str2 : str1;
            int length = shortStr.length();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < length; i++) {
                for (int x = 0, y = length - i; y <= length; x++, y++) {
                    String str = shortStr.substring(x, y);
                    if (longStr.contains(str)) {
                        sb.append(str + ",");
                    }
                }
                //不为空 就是找到最大子串了 退出循环
                if (sb.length() != 0) {
                    break;
                }
            }
            return sb.toString().replaceAll(",$", "").split(",");
        }
        return null;
    }
}
